package com.roy.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author ：楼兰
 * @date ：Created in 2021/8/5
 * @description:
 **/

public class FileIODemo3 {
    public static void main(String[] args) throws IOException {
        File f = new File("D://test1.txt");
        if(!f.exists()){
            f.createNewFile();
        }
        RandomAccessFile raf = new RandomAccessFile(f,"rw");
        final FileChannel fc = raf.getChannel();

        fc.map(FileChannel.MapMode.READ_WRITE,0,5);
        final ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        for (int i = 0; i < 100; i++) {
            byteBuffer.put(i,(byte)'a');
        }
        System.out.println(byteBuffer.toString());
        //这里也是将数据缓存到一起，进行一次write系统调用。
        fc.position(0).write(byteBuffer);
        //这个force方法会真正触发一次fsync系统调用，将数据写入硬盘。
        fc.force(true);
        fc.close();
        raf.close();
    }
}
